from flask import Blueprint, request, render_template, redirect, url_for, jsonify, current_app, flash
from flask_login import login_user, logout_user, login_required, current_user
from werkzeug.security import check_password_hash, generate_password_hash
from app.models import Doctor, db
from app.utils import custom_jsonify

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        if current_user.is_authenticated:
            return redirect(url_for('ward.homepage'))
        return render_template('index.html')
    
    try:
        # 获取请求数据
        if request.is_json:
            data = request.get_json()
        else:
            data = request.form

        doctor_id = data.get('doctor_id')
        password = data.get('password')
        
        # 输入验证
        if not doctor_id or not password:
            return custom_jsonify({"msg": "failed", "error": "请输入用户名和密码"}, 400)

        # 查询用户
        doctor = Doctor.query.filter_by(doctor_id=doctor_id).first()
        
        # 测试���境：如果用户不存在，创建用户（仅用于测试）
        if not doctor and current_app.config['ENV'] == 'development':
            doctor = Doctor(
                doctor_id=doctor_id,
                doctor_name="测试医生",
                dept_name="测试科室",
                type="主任医师",
                ward_id=None
            )
            doctor.set_password(password)
            db.session.add(doctor)
            try:
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                current_app.logger.error(f"Error creating test user: {str(e)}")
                return custom_jsonify({"msg": "failed", "error": "创建测试用户失败"}, 500)
        
        # 验证密码
        if doctor and (current_app.config['ENV'] == 'development' or 
                      doctor.check_password(password)):
            login_user(doctor)
            
            next_page = request.args.get('next')
            if next_page:
                return redirect(next_page)
                
            if request.is_json:
                return custom_jsonify({
                    "msg": "success",
                    "doctor_info": {
                        "doctor_id": doctor.doctor_id,
                        "doctor_name": doctor.doctor_name,
                        "dept_name": doctor.dept_name,
                        "type": doctor.type
                    }
                })
            return redirect(url_for('ward.homepage'))
            
        return custom_jsonify({"msg": "failed", "error": "用户名或密码错误"}, 401)
        
    except Exception as e:
        current_app.logger.error(f"Login error: {str(e)}")
        return custom_jsonify({"msg": "failed", "error": "登录失败，请稍后重试"}, 500)

@auth_bp.route('/auth/logout', methods=['POST'])
@login_required
def logout():
    try:
        logout_user()
        return custom_jsonify({
            "msg": "success",
            "message": "退出成功"
        })
    except Exception as e:
        current_app.logger.error(f"Logout error: {str(e)}")
        return custom_jsonify({
            "msg": "failed",
            "error": "退出失败，请稍后重试"
        }, 500)

@auth_bp.route('/auth/check_auth')
def check_auth():
    if current_user.is_authenticated:
        return custom_jsonify({
            "msg": "success",
            "authenticated": True,
            "doctor_info": {
                "doctor_id": current_user.doctor_id,
                "doctor_name": current_user.doctor_name,
                "dept_name": current_user.dept_name,
                "type": current_user.type
            }
        })
    return custom_jsonify({
        "msg": "failed",
        "authenticated": False
    }, 401) 

@auth_bp.route('/auth/test')
def test():
    print(current_user)
    print(type(current_user))